package com.eqdd.yiqidian.ui.gongneng.renshi.meeting

import android.app.Activity
import android.app.AlertDialog
import android.content.Intent
import android.support.v7.widget.RecyclerView
import android.view.KeyEvent
import android.view.View
import com.bigkoo.pickerview.TimePickerView
import com.eqdd.yiqidian.R
import com.eqdd.yiqidian.adapter.slimadapter.SlimInjector
import com.eqdd.yiqidian.base.Config
import com.eqdd.yiqidian.bean.DepartmentStaffTreeBean
import com.eqdd.yiqidian.bean.MeetingTypeInfoBean
import com.eqdd.yiqidian.bean.rebuild.slimedit.SlimEditCheckButtonBean
import com.eqdd.yiqidian.bean.rebuild.slimedit.SlimEditEnterBean
import com.eqdd.yiqidian.bean.rebuild.slimedit.SlimTimeSelectBean
import com.eqdd.yiqidian.http.DialogCallBack
import com.eqdd.yiqidian.http.HttpConfig
import com.eqdd.yiqidian.http.HttpResult
import com.eqdd.yiqidian.ui.MultiSelectListActivity
import com.eqdd.yiqidian.ui.base.SlimBaseMultiEditActivity
import com.eqdd.yiqidian.ui.tongxunlu.stafftree.StaffTreeMultiActivity
import com.eqdd.yiqidian.ui.tongxunlu.stafftree.StaffTreeSingleActivity
import com.eqdd.yiqidian.utils.TimeUtil
import com.eqdd.yiqidian.widget.ChooseAlertView
import com.jhj.datalibrary.tree.multi.BaseMultiTreeActivity
import com.kyleduo.switchbutton.SwitchButton
import com.lzy.okgo.OkGo
import com.lzy.okgo.model.Response
import kotlinx.android.synthetic.main.activity_recyclerview.*
import kotlinx.android.synthetic.main.activity_title.*
import org.jetbrains.anko.sdk25.coroutines.onClick
import org.jetbrains.anko.startActivityForResult
import org.jetbrains.anko.toast
import java.text.SimpleDateFormat
import java.util.*

class MeetingTypeInfoActivity : SlimBaseMultiEditActivity() {

    private var upDate: Date? = null
    private var downDate: Date? = null
    private var isUpper: Boolean = false
    private var frequency: String = ""


    private var person: ArrayList<DepartmentStaffTreeBean>? = arrayListOf()
    private var month: String? = null
    private var week: String? = null

    private var isEditFinish = true
    private var isUpdate = false


    override fun initBinding() {
        clearData()
        setContentView(R.layout.activity_recyclerview)
        back.visibility = View.VISIBLE
        back.onClick {
            finishActivity()
        }
        tv_title.text = "会议类别"
    }

    override fun initRecyclerView(): RecyclerView {
        return recyclerView
    }

    private var meetingId: Int = -1

    override fun initData() {
        super.initData()


        meetingId = intent.getIntExtra(Config.ID, -1)
        if (meetingId == -1) {
            finish()
            toast("获取详情失败")
            return

        }
        OkGo.post<HttpResult<MeetingTypeInfoBean>>(HttpConfig.BASE_URL + HttpConfig.MEETING_TYPE_INFO)
                .params("companyId", user.companyId)
                .params("mettingId", meetingId)
                .execute(object : DialogCallBack<HttpResult<MeetingTypeInfoBean>>(this@MeetingTypeInfoActivity) {
                    override fun onSuccess(response: Response<HttpResult<MeetingTypeInfoBean>>?) {
                        val result = response?.body()
                        if (result?.status == 200) {
                            infoBean = result.items
                            setEditBeans()
                        }
                    }
                })
    }


    override fun itemClick(p: Int) {
        when (slimAdapterEx.data[p].position) {
            1 -> {
                val array = arrayOf("每月", "每周", "每天", "一次")
                ChooseAlertView.getBottomChoose(this, null, array) { o, pos ->
                    if (frequency != array[pos - 1]) {
                        slimAdapterEx.getDataItem(2).content = ""
                        slimAdapterEx.notifyItemChanged(2)
                        month = null
                        week = null
                        isEditFinish = false
                    }
                    frequency = array[pos - 1]
                    slimAdapterEx.getDataItem(1).content = array[pos - 1]
                    slimAdapterEx.getDataItem(1).tag = pos
                    slimAdapterEx.notifyItemChanged(1)
                    if (pos == 4) {
                        isEditFinish = true
                        slimAdapterEx.getDataItem(2).content = "一次"
                        slimAdapterEx.notifyItemChanged(2)
                        updateData("frequency='${slimAdapterEx.getDataItem(1).tag as Int}';timeInterval='一次'")
                    }
                    slimAdapterEx.getDataItem(1).content
                }.show()

            }
            2 -> {
                val tag = slimAdapterEx.getDataItem(1).tag as? Int
                if (tag == null) {
                    toast("请选择会议频率")
                    return
                }
                isEditFinish = true
                when (tag) {
                    1 -> {
                        val array = resources.getStringArray(R.array.month)
                        startActivityForResult<MultiSelectListActivity>(997, "data" to array, "select" to month)
                    }
                    2 -> {
                        val array = resources.getStringArray(R.array.week)
                        startActivityForResult<MultiSelectListActivity>(998, "data" to array, "select" to week)
                    }
                    3 -> {
                        val array = arrayOf("上午", "下午")
                        ChooseAlertView.getBottomChoose(this, null, array) { o, pos ->
                            slimAdapterEx.getDataItem(2).content = array[pos - 1]
                            slimAdapterEx.notifyItemChanged(2)
                            updateData("frequency='${tag}';timeInterval='${array[pos - 1]}'")
                        }.show()
                    }
                }


            }
            3 -> {
                isUpper = true
                openTimePicker()
            }
            4 -> {
                isUpper = false
                openTimePicker()
            }
            6 -> {
                startActivityForResult<StaffTreeMultiActivity>(999, Config.TITLE to "参与人员", Config.ID to 0, Config.TYPE to StaffTreeMultiActivity.TYPE_CANYUREN, BaseMultiTreeActivity.SELECTED_DATA to person)
            }
            7 -> {
                startActivityForResult<StaffTreeSingleActivity>(1000, Config.TITLE to "主持人", Config.ID to 0, Config.TYPE to StaffTreeSingleActivity.TYPE_SINGLE_SELECT)
            }
            8 -> {
                startActivityForResult<StaffTreeSingleActivity>(1001, Config.TITLE to "记录人", Config.ID to 0, Config.TYPE to StaffTreeSingleActivity.TYPE_SINGLE_SELECT)
            }
            10 -> {
                startActivityForResult<StaffTreeSingleActivity>(1002, Config.TITLE to "发布人", Config.ID to 0, Config.TYPE to StaffTreeSingleActivity.TYPE_SINGLE_SELECT)
            }


        }
    }

    var infoBean: MeetingTypeInfoBean? = null


    override fun setEditBeans() {


        infoBean?.let {

            val frequency = when {
                1 == it.frequency -> "每月"
                2 == it.frequency -> "每周"
                3 == it.frequency -> "每天"
                else -> "一次"
            }

            val builder = StringBuilder()
            it.attendees.forEach { att ->
                val bean = DepartmentStaffTreeBean()
                builder.append(att.username).append(",")
                bean.id = att.userGuid
                bean.content = att.username
                bean.icon = att.headImage
                person?.add(bean)
            }



            datas.add(SlimEditEnterBean("会议类型", it.type, 0, "请输入").setNeed(true))
            datas.add(SlimEditEnterBean("会议频率", frequency, 1, "请选择").setDeal(true).setNeed(true).setTag(it.frequency))
            datas.add(SlimEditEnterBean("会议时段", it.timeInterval, 2, "请选择").setDeal(true).setNeed(true))
            datas.add(SlimTimeSelectBean("会议开始时间", TimeUtil.formatWebTime1(it.startTime), 3, "请选择").setStartTime(true).setDeal(true).setNeed(true))
            datas.add(SlimTimeSelectBean("会议结束时间", TimeUtil.formatWebTime1(it.endTime), 4, "选择择").setStartTime(false).setDeal(true).setNeed(true))
            datas.add(SlimEditEnterBean("会议地点", it.place, 5, "请输入").setNeed(true))
            datas.add(SlimEditEnterBean("参与人员", builder.substring(0, builder.length - 1), 6, "请选择").setDeal(true).setNeed(true))
            datas.add(SlimEditEnterBean("主持人", it.compere.username, 7, "请选择").setDeal(true).setNeed(true))
            datas.add(SlimEditEnterBean("记录人", it.recorder.username, 8, "请选择").setDeal(true).setNeed(true))
            datas.add(SlimEditEnterBean("会议目的", it.aim, 9, "请输入").setNeed(true))
            datas.add(SlimEditEnterBean("会议通知发布人", it.admin.username, 10, "请选择").setDeal(true).setNeed(true))
            datas.add(SlimEditCheckButtonBean("是否提预案", "", 11, it.isMotion).setDeal(true))
            slimAdapterEx
                    .register(R.layout.list_item_24, SlimInjector<SlimEditCheckButtonBean> { data, injector ->
                        injector?.text(R.id.tv_left_center_content, data?.title)
                                ?.checked(R.id.sb_end, data?.isCheck == true)
                                ?.with<SwitchButton>(R.id.sb_end) {
                                    it.setOnCheckedChangeListener { view, isChecked ->
                                        (slimAdapterEx.getDataItem(11) as SlimEditCheckButtonBean).isCheck = isChecked
                                        updateData("motion='${isChecked}'")
                                    }
                                }

                    })

            slimAdapterEx.register(R.layout.list_item_29, SlimInjector<SlimTimeSelectBean> { data, injector ->
                injector?.text(R.id.tv_left_content, data?.title)
                        ?.text(R.id.tv_right_content, data?.content)
                        ?.hint(R.id.tv_right_content, data?.hint)
            })
            slimAdapterEx.notifyDataSetChanged()
        }

    }

    private fun parseData(time: String?): Calendar? {
        if (time == null) {
            return null
        }
        val array = time.split(":")
        val calendar = Calendar.getInstance()
        calendar.set(Calendar.HOUR_OF_DAY, array[0].toInt())
        calendar.set(Calendar.MINUTE, array[1].toInt())
        return calendar

    }


    private fun openTimePicker() {
        val sf = SimpleDateFormat("HH:mm", Locale.CHINA)
        val now = Calendar.getInstance()
        upDate = parseData(slimAdapterEx.getDataItem(3).content)?.time
        downDate = parseData(slimAdapterEx.getDataItem(4).content)?.time
        if (isUpper) {
            now.time = upDate
        } else {
            now.time = downDate
        }
        TimePickerView.Builder(this, TimePickerView.OnTimeSelectListener { date, v ->
            val calendar = Calendar.getInstance()
            calendar.set(Calendar.HOUR_OF_DAY, date.hours)
            calendar.set(Calendar.MINUTE, date.minutes)
            if (isUpper) {
                if (calendar.time?.after(downDate) == true) {
                    toast("开始时间小于结束事件，请重新选择")
                    return@OnTimeSelectListener
                }
                upDate = date
                slimAdapterEx.getDataItem(3).content = sf.format(date)
                slimAdapterEx.notifyItemChanged(3)
                updateData("startTime='${sf.format(date)}'")
            } else {
                if (calendar.time?.before(upDate) == true) {
                    toast("开始时间小于结束事件，请重新选择")
                    return@OnTimeSelectListener
                }
                downDate = date
                slimAdapterEx.getDataItem(4).content = sf.format(date)
                slimAdapterEx.notifyItemChanged(4)
                updateData("startTime='${sf.format(date)}'")
            }

        })
                .setOutSideCancelable(true)
                .setType(booleanArrayOf(false, false, false, true, true, false))
                .setDate(now)
                .build()
                .show()
    }

    fun updateData(params: String) {
        OkGo.post<HttpResult<*>>(HttpConfig.BASE_URL + HttpConfig.MEETING_TYPE_UPDATE)
                .params("userGuid", user.guid)
                .params("companyId", user.companyId)
                .params("mettingId", meetingId)
                .params("para", params)
                .execute(object : DialogCallBack<HttpResult<*>>(this) {
                    override fun onSuccess(response: Response<HttpResult<*>>?) {
                        val result = response?.body()
                        if (result?.status == 200) {
                            toast("修改成功")
                            isUpdate = true
                        }
                    }
                })
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (data == null)
            return
        if (resultCode == RESULT_OK) {
            when (requestCode) {
                997 -> {
                    month = data.getStringExtra("data")
                    datas[2].content = month
                    slimAdapterEx.notifyItemChanged(2)
                    updateData("frequency='${slimAdapterEx.getDataItem(1).tag as Int}';timeInterval='${month}'")
                }
                998 -> {
                    week = data.getStringExtra("data")
                    datas[2].content = week
                    slimAdapterEx.notifyItemChanged(2)
                    updateData("frequency='${slimAdapterEx.getDataItem(1).tag as Int}';timeInterval='${week}'")
                }
                999 -> {//参与人员
                    person = data.getSerializableExtra(BaseMultiTreeActivity.SELECTED_DATA) as ArrayList<DepartmentStaffTreeBean>
                    val id = StringBuilder()
                    val name = StringBuilder()
                    person?.forEach {
                        id.append(it.id).append(",")
                        name.append(it.name).append(",")
                    }
                    datas[6].content = name.substring(0, name.length - 1)
                    datas[6].tag = id.substring(0, id.length - 1)
                    slimAdapterEx.notifyItemChanged(6)
                    updateData("attendees='${datas[6].tag}'")
                }
                1000 -> {//主持人
                    val hostMan = data.getSerializableExtra("data") as DepartmentStaffTreeBean?
                    datas[7].content = hostMan?.name
                    datas[7].tag = hostMan?.id
                    slimAdapterEx.notifyItemChanged(7)
                    updateData("compere='${hostMan?.id}'")

                }
                1001 -> {//记录人
                    val recordMan = data.getSerializableExtra("data") as DepartmentStaffTreeBean?
                    datas[8].content = recordMan?.name
                    datas[8].tag = recordMan?.id
                    slimAdapterEx.notifyItemChanged(8)
                    updateData("recorder='${recordMan?.id}'")
                }
                1002 -> {//发布人
                    val publishMan = data.getSerializableExtra("data") as DepartmentStaffTreeBean?
                    datas[10].content = publishMan?.name
                    datas[10].tag = publishMan?.id
                    slimAdapterEx.notifyItemChanged(10)
                    updateData("admin='${publishMan?.id}'")
                }
            }
        }
        if (resultCode == Config.INTENT_CONTENT) {
            val content = data.getStringExtra("content")
            when (requestCode) {
                0 -> updateData("type='${content}'")
                5 -> updateData("place='${content}'")
                9 -> updateData("aim='${content}'")
            }
        }
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            finishActivity()
        }
        return super.onKeyDown(keyCode, event)
    }

    private fun finishActivity() {
        if (!isEditFinish) { //编辑未完成退出
            AlertDialog.Builder(this)
                    .setTitle("提示")
                    .setMessage("会议时段没有编辑，会议频率将不会自动保存，是否退出")
                    .setNegativeButton("取消") { dialog, which ->
                        dialog.dismiss()
                    }
                    .setPositiveButton("确定") { dialog, which ->
                        dialog.dismiss()
                        finish()
                    }
                    .show()
        } else if (isUpdate) { //做出修改，退出刷新界面
            setResult(Activity.RESULT_OK)
            finish()
        }
    }

}